import { ref, onMounted, onBeforeUnmount } from "vue";

// 重连间隔配置
const RECONNECT_INTERVALS = [1000, 2000, 4000, 8000, 16000, 30000];
const MAX_RECONNECT_ATTEMPTS = 5;
const HEARTBEAT_INTERVAL = 30000;
const HEARTBEAT_TIMEOUT = 3000;

/**
 * WebSocket客户端Hook
 * @param {string} moduleType - 模块类型（如'chat'、'notify'等）
 * @param {string} baseUrl - WebSocket服务器地址
 * @returns {Object} WebSocket相关状态和方法
 */
export function useWebSocket(
  moduleType,
  baseUrl = import.meta.env.VITE_API_BASE_WS_URL
) {
  const ws = ref(null);
  const connected = ref(false);
  const reconnecting = ref(false);
  const messageHandlers = new Map();
  const offlineQueue = ref([]);
  const shouldReconnect = ref(true);
  const MAX_QUEUE_SIZE = 1000;
  let reconnectAttempts = 0;
  let heartbeatTimer = null;
  let heartbeatTimeoutTimer = null;

  // 创建WebSocket连接
  const connect = () => {
    const url = `${baseUrl}/ws?module=${moduleType}`;
    ws.value = new WebSocket(url);

    ws.value.onopen = () => {
      console.log(`[${moduleType}] WebSocket连接已建立`);
      connected.value = true;
      reconnecting.value = false;
      reconnectAttempts = 0;
      startHeartbeat();
      processOfflineQueue();
    };

    ws.value.onclose = () => {
      console.log(`[${moduleType}] WebSocket连接已关闭`);
      connected.value = false;
      clearHeartbeat();
      if (shouldReconnect.value) {
        attemptReconnect();
      }
    };

    ws.value.onerror = (error) => {
      console.error(`[${moduleType}] WebSocket错误:`, error);
    };

    ws.value.onmessage = (event) => {
      let data;
      try {
        data = JSON.parse(event.data);
      } catch (error) {
        console.error(`[${moduleType}] 消息解析错误:`, error);
        return;
      }

      // 处理心跳响应
      if (data.type === "pong") {
        clearTimeout(heartbeatTimeoutTimer);
        return;
      }

      // 处理错误消息
      if (data.type === "error") {
        console.error(`[${moduleType}] 服务器错误:`, data);
        return;
      }
      // 调用消息处理器
      const handler = messageHandlers.get(data.type);
      if (handler) {
        handler(data.payload);
      }
    };
  };

  // 发送消息
  const sendMessage = (type, payload) => {
    const message = {
      type,
      module: moduleType,
      payload,
      timestamp: Date.now(),
    };

    if (connected.value && ws.value?.readyState === WebSocket.OPEN) {
      ws.value.send(JSON.stringify(message));
    } else if (offlineQueue.value.length < MAX_QUEUE_SIZE) {
      offlineQueue.value.push(message);
    } else {
      console.warn(`[${moduleType}] 离线消息队列已满，消息已丢弃`);
    }
  };

  // 注册消息处理器
  const onMessage = (type, handler) => {
    messageHandlers.set(type, handler);
    // console.log(`[${moduleType}] 注册消息处理器:`, type, messageHandlers);
  };

  // 发送心跳
  const startHeartbeat = () => {
    heartbeatTimer = setInterval(() => {
      if (connected.value) {
        sendMessage("ping");
        heartbeatTimeoutTimer = setTimeout(() => {
          console.warn(`[${moduleType}] 心跳超时，正在重连...`);
          ws.value?.close();
        }, HEARTBEAT_TIMEOUT);
      }
    }, HEARTBEAT_INTERVAL);
  };

  // 清理心跳定时器
  const clearHeartbeat = () => {
    if (heartbeatTimer) {
      clearInterval(heartbeatTimer);
      heartbeatTimer = null;
    }
    if (heartbeatTimeoutTimer) {
      clearTimeout(heartbeatTimeoutTimer);
      heartbeatTimeoutTimer = null;
    }
  };

  // 重连逻辑
  const attemptReconnect = () => {
    if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
      console.error(`[${moduleType}] 重连次数超过限制，请手动重连`);
      return;
    }

    reconnecting.value = true;
    const delay =
      RECONNECT_INTERVALS[
        Math.min(reconnectAttempts, RECONNECT_INTERVALS.length - 1)
      ];

    setTimeout(() => {
      console.log(`[${moduleType}] 尝试重连...`);
      reconnectAttempts++;
      connect();
    }, delay);
  };

  // 处理离线消息队列
  const processOfflineQueue = () => {
    while (offlineQueue.value.length > 0) {
      const message = offlineQueue.value.shift();
      sendMessage(message.type, message.payload);
    }
  };

  // 手动重连
  const reconnect = () => {
    if (ws.value) {
      ws.value.close();
    }
    reconnectAttempts = 0;
    connect();
  };

  // 生命周期钩子
  onMounted(() => {
    connect();
  });

  onBeforeUnmount(() => {
    shouldReconnect.value = false;
    if (ws.value) {
      ws.value.close();
    }
    clearHeartbeat();
    messageHandlers.clear();
    offlineQueue.value = [];
  });

  return {
    connected,
    reconnecting,
    sendMessage,
    onMessage,
    reconnect,
    offlineQueue,
  };
}
